package com.oraycn.esbasic.utils;

import java.nio.ByteOrder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class BufferUtils {
    /**
     * 使用统一的方法构造ByteBuf 方便后续修改
     * @return
     */
	public static ByteBuf newBuffer(){
        //设置ByteBuf默认初始化大小为128，如果设置的过小，写入数据时会照成频繁的内存分配和memoryCopy
        return Unpooled.buffer(128).order(ByteOrder.LITTLE_ENDIAN);
    }

    public static ByteBuf newBuffer(int buffSize){
        return Unpooled.buffer(buffSize).order(ByteOrder.LITTLE_ENDIAN);
    }

    public static ByteBuf wrappedBuffer(ByteBuf... bufs){
        return Unpooled.wrappedBuffer(bufs);
    }

    public static ByteBuf wrappedBuffer(byte[] bufs){
        return Unpooled.wrappedBuffer(bufs).order(ByteOrder.LITTLE_ENDIAN);
    }

    public static byte[] getValidData(ByteBuf buf)
    {
        byte[] res = new byte[buf.readableBytes()] ;
        System.arraycopy(buf.array() ,0,res,0,res.length);
        return res ;
    }
}
